package com.xlh.virtualization.websocket;

import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import com.xlh.virtualization.job.delayed.StopContainerListener;
import com.xlh.virtualization.job.delayed.StopContainerTask;
import com.xlh.websocket.GetHttpSessionConfigurator;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import static com.xlh.virtualization.constant.ContextTypeEnum.QUESTION;

/**
 * 考试实验WebSocket，用于停止容器
 *
 * @author cheer
 */
@ServerEndpoint(value = "/ws/experiment/question/{questionId}", configurator = GetHttpSessionConfigurator.class)
@Component
public class QuestionExperimentWebsocket {

    /**
     * 存储连接 userId questionId 数量
     */
    private static Table<Long, Long, Integer> connectionNumberMap = HashBasedTable.create();

    /**
     * 用户Id
     */
    private Long userId;

    /**
     * 试题Id
     */
    private Long questionId;

    @OnOpen
    public void onOpen(@PathParam("questionId") Long questionId, EndpointConfig config) {
        this.userId = (Long) config.getUserProperties().get("userId");
        this.questionId = questionId;

        synchronized (QuestionExperimentWebsocket.class) {
            if (connectionNumberMap.contains(userId, questionId)) {
                int number = connectionNumberMap.get(userId, questionId);
                connectionNumberMap.put(userId, questionId, number + 1);
            } else {
                connectionNumberMap.put(userId, questionId, 1);
            }
        }
    }

    @OnClose
    public void onClose() {
        synchronized (QuestionExperimentWebsocket.class) {
            Integer number = connectionNumberMap.get(userId, questionId);
            if (number == null || number - 1 <= 0) {
                connectionNumberMap.remove(userId, questionId);

                // 停止容器
                StopContainerListener.putTask(new StopContainerTask(userId, QUESTION.getCode(), questionId));
            } else {
                connectionNumberMap.put(userId, questionId, number - 1);
            }
        }
    }

    @OnMessage
    public void onMessage(String jsonStr, Session session) {
        // 暂时不需要实现该方法
    }

    @OnError
    public void onError(Session session, Throwable error) {
        // 暂时不需要实现该方法
    }

    public static Boolean isOnline(Long userId, Long questionId) {
        return connectionNumberMap.contains(userId, questionId);
    }
}
